package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author hd
 */
public class SimpleRedisLock implements ILock{
    private final StringRedisTemplate stringRedisTemplate;
    private final String name;
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String s, StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = s;
    }

    @Override
    public boolean tryLock(Long time) {
        // 获取锁
        String key = KEY_PREFIX + name;
        String value = ID_PREFIX+Thread.currentThread().getId();
        Boolean flag =stringRedisTemplate.opsForValue().setIfAbsent(key, value,time, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }
    @Override
    public void unLock() {
        //调用lua脚本保证判断与删除的原子性
        String key = KEY_PREFIX + name;
        String value = ID_PREFIX+Thread.currentThread().getId();
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(key),value);
    }
//    @Override
//    public void unLock() {
//        String key = KEY_PREFIX + name;
//        String value = ID_PREFIX+Thread.currentThread().getId();
//        var value2 = stringRedisTemplate.opsForValue().get(key);
//        if (value.equals(value2)){
//            stringRedisTemplate.delete(key);
//        }
//    }
}
